<template>
  <view class="mail-list" v-if="isOpen" :class="{selected: contacts.length > 0}">
    <u-index-list :scrollTop="scrollTop" active-color="#FBB000" :index-list="indexList">
      <view v-for="(item, index) in contacts" :key="index">
        <u-index-anchor :index="item.letter" />
        <block v-for="(i, k) in item.contacts" :key="k">
          <view class="list-cell">
            <text>{{i.name}}</text>
            <view class="btn" @click="onChangeItem(i)"><text>邀请</text></view>
          </view>
        </block>
      </view>
    </u-index-list>
    
    <view style="margin-top: 150rpx; text-align: center;" v-if="contacts.length < 1"><text style="font-size: 30rpx;color: #666;">暂无手机联系人</text></view>
    
    <!-- 确定 -->
    <view class="footer" v-if="contacts.length > 0">
      <view class="btn-box">
        <view class="btn flex flex-ai-c flex-jc-c" @click="onOnekeyInvite">
          <text class="text">一键邀请</text>
        </view>
      </view>
    </view>
  </view>
  <view class="mail-list selected" v-else>
    <u-empty mode="permission" style="margin-top: 150rpx;" text="请开启通讯录访问权限"></u-empty>
    
    <!-- 确定 -->
    <view class="footer">
      <view class="btn-box">
        <view class="btn flex flex-ai-c flex-jc-c" @click="onAddressBookSetting">
          <text class="text">去开启</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import pinyin from '@/utils/pinyin/pinyin3.js'
import pinyin1 from '@/utils/pinyin/Convert_Pinyin.js'
let platform = uni.getSystemInfoSync().platform
export default {
  data() {
    return {
      scrollTop: 0,
      /* 联系人 */
      contacts: [],
      contactItems: [],
      indexList: [],
      selected: [] ,// 已选联系人
      inviteLink: 'https://files.yzsheng.com/shareH5/Qmc_Client_H5/index.html', // 邀请链接
      isOpen: true
    }
  },
  onLoad(option) {
    if(option.inviteCode) {
      this.inviteLink += '?code=' + option.inviteCode
    } else {
      this.$api.user.GetUserInfomation().then(data => {
        this.inviteLink = '?code=' + data.data.invitecode
      }).catch(err => {})
    }
    this.initContacts()
  },
  methods: {
    /* 
     * 初始化通讯录
     */
    initContacts() {
      //获取手机通讯录
      plus.contacts.getAddressBook(plus.contacts.ADDRESSBOOK_PHONE, (addressbook) => {
        // 可通过addressbook进行通讯录操作
        addressbook.find(["displayName", "phoneNumbers"], (contacts) => {
          let items = [];
          for (let i = 0; i < contacts.length; i++) {
            if (contacts[i].phoneNumbers.length > 0) {
              let contact = {
                'name': contacts[i].displayName || contacts[i].phoneNumbers[0].value.replace(/\s*/g,''),
                'phone': contacts[i].phoneNumbers[0].value.replace(/\s*/g,''),
                'selected': false
              };
              items.push(contact);
            }
          }
          // this.contacts = pinyin.paixu(items)
          // this.contacts.sort(function(o1, o2) {
          //   return o1.letter.charCodeAt(0) - o2.letter.charCodeAt(0)
          // })
          // let arr = this.contacts.concat(this.contacts.shift())
          // this.contacts = arr
          // this.contactItems = JSON.parse(JSON.stringify(this.contacts))
          // this.indexList = this.contactItems.map(item => {
          //   return item.letter
          // })
          this.contacts = this.pySort(items)
          this.contactItems = JSON.parse(JSON.stringify(this.contacts))
          this.indexList = this.contactItems.map(item => {
            return item.letter
          })
        }, (e) => {
          // this.onAddressBookSetting()
          this.isOpen = false
        });
      }, (e) => {
        // this.onAddressBookSetting()
        this.isOpen = false
      });
    },
    /*
     * 权限设置
     */
    onAddressBookSetting() {
      if (this.isShow) {
        return
      }
      this.isShow = true
      uni.showModal({
        title: '提示',
        content: 'APP通讯录权限没有开启，是否开启？',
        success(res) {
          if (res.confirm) {
            if (platform == 'ios') {
              var UIApplication = plus.ios.import("UIApplication");
              var NSURL2 = plus.ios.import("NSURL");
              var setting2 = NSURL2.URLWithString("app-settings:");
              var application2 = UIApplication.sharedApplication();
              application2.openURL(setting2);
              plus.ios.deleteObject(setting2);
              plus.ios.deleteObject(NSURL2);
              plus.ios.deleteObject(application2);
            } else {
              var main = plus.android.runtimeMainActivity();
              var bulid = plus.android.importClass("android.os.Build");
              var Intent = plus.android.importClass('android.content.Intent');
              if (bulid.VERSION.SDK_INT >= 9) {
                var intent = new Intent('android.settings.APPLICATION_DETAILS_SETTINGS');
                var Uri = plus.android.importClass('android.net.Uri');
                var uri = Uri.fromParts("package", main.getPackageName(), null)
                intent.setData(uri);
                intent.putExtra('android.content.Intent.setFlags', Intent.FLAG_ACTIVITY_NEW_TASK);
              } else if (bulid.VERSION.SDK_INT <= 8) {
                var intent = new Intent(Intent.ACTION_VIEW);
                intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
                intent.putExtra("com.android.settings.ApplicationPkgName", main.getPackageName());
                intent.putExtra('android.content.Intent.setFlags', Intent.FLAG_ACTIVITY_NEW_TASK);
              }
              main.startActivity(intent);
              this.isShow = false
            }
            this.isOpen = true
          } else {
            uni.navigateBack({
              delta: 1
            })
          }
        }
      })
    },
    // 点击联系人
    onChangeItem(data) {
      this.onClickSendSms([data.phone])
    },
    // 一键发送
    onOnekeyInvite() {
      let mobile = []
      this.contacts.map(item => {
        item.contacts.map(i => {
          mobile.push(i.phone)
        })
      })
      this.onClickSendSms(mobile)
    },
    // 发送短信
    onClickSendSms(mobile) {
      uni.showModal({
        content: '是否确定邀请该用户？',
        success: async res => {
          if(res.confirm){
            uni.showLoading({
              title: '发送中'
            })
            try{
              let res = await this.$api.user.InviteMemberSendMsg({
                mobiles: mobile,
                url: this.inviteLink
              })
              uni.hideLoading()
              uni.showToast({
                icon: 'none',
                title: res.data
              })
            }catch(e){
              uni.hideLoading()
            }
          }
        }
      })
    },
    isChinese(temp) {
      var re = /[^\u4E00-\u9FA5]/
      if (re.test(temp)) {
        return false
      }
      return true
    },
    isChar(char) {
      var reg = /[A-Za-z]/
      if (!reg.test(char)) {
        return false
      }
      return true
    },
    pySort(list) {
      var $this = this
      if (!String.prototype.localeCompare) {
        return null
      }
      var letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ#'.split('') //ABCDEFGHJKLMNOPQRSTWXYZ
      var zh = '阿八嚓哒妸发旮哈*讥咔垃痳拏噢妑七呥涩它**穵夕丫帀'.split('')
      var result = []
      let tr = ''
      var curr
      
      for (let i = 0; i < letters.length; i++) {
        curr = {
          letter: letters[i],
          contacts: []
        } //字母对象，data数据
        
        list.forEach(n => {
          let name = n.name || '1'
          name = this.$u.trim(name, 'all')
          let initial = name.charAt(0) //截取第一个字符
          
    
          if (initial === letters[i] || initial === letters[i].toLowerCase()) { //首字符是英文的
            curr.contacts.push(n)
          }
          if (zh[i] !== '*' && $this.isChinese(initial)) { //判断是否是无汉字,是否是中文
    
            let chinaName = pinyin1.chineseToPinYin(initial).charAt(0) //直接使用pinyin中方法
            
            if (chinaName === letters[i] || chinaName === letters[i].toLowerCase()) { //首字符是英文的
              curr.contacts.push(n)
    
            }
    
          }
          if (letters[i] === '#' && !$this.isChar(initial) && !$this.isChinese(initial)) {
            curr.contacts.push(n)
          }
        })
        result.push(curr)
    
      }
      result = result.filter(item => {
        return item.contacts.length > 0
      })
      return result
    }
  },
  onPageScroll(e) {
    this.scrollTop = e.scrollTop;
  }
}
</script>

<style lang="scss" scoped>
.mail-list{
  overflow: hidden;
  .list-cell {
    display: flex;
    box-sizing: border-box;
    width: 100%;
    padding: 10px 24rpx;
    overflow: hidden;
    color: #333;
    font-size: 28rpx;
    height: 90rpx;
    background-color: #fff;
    align-items: center;
    justify-content: space-between;
    .btn{
      width: 146rpx;
      height: 54rpx;
      background: linear-gradient(0deg, #FBD220, #FFE23E);
      border-radius: 27rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 26rpx;
      margin-right: 54rpx;
    }
  }
  &.selected {
    padding-bottom: 120rpx;
    padding-bottom: calc(constant(safe-area-inset-bottom) + 120rpx);
    padding-bottom: calc(env(safe-area-inset-bottom) + 120rpx);
  }
  .footer{
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    padding-bottom: 0;
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
    background-color: #fff;
    .btn-box{
      padding: 16rpx 24rpx;
      .btn{
        height: 88rpx;
        background: linear-gradient(0deg, #FBD220, #FFE23E);
        border-radius: 44rpx;
        .text{
          font-size: 32rpx;
          color: #333;
          margin-left: 16rpx;
        }
      }
    }
  }
}
</style>
